package com.handpay.zztong.hp.swiper.widget;



import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.swiper.activity.ConnectSwiperActivity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

// 自定义的SurfaceView子类  
public class BindDeviceVoiceView extends SurfaceView implements Callback{

	
	private Bitmap cardImage;
	private Bitmap titleImage;
	private Bitmap vposImage;
//	private Bitmap vposImageFront;
	private Bitmap phoneImage;
	private Bitmap backImage;
	
	
	private int topPosition = 0;
	private int spacePostion = 0;
	private int top=0;
	private boolean isSwiperOn = false;
	private boolean isBack = false;
	SurfaceHolder surfaceHolder;
	float rotate = 0;
	private int state = -1;
	private MyThread thread = null;
	private int praitTime = 25;
	public static int frameCount = 0;
	private float backLeftMin,backLeftMax,backHeightMax,backHeightMin;
	private Context context;
	private int icCardWidth = -1;
	private boolean isVposIC = false;
	
	public BindDeviceVoiceView(Context context) {
		super(context);
		this.context = context;
		surfaceHolder = this.getHolder();// 获取holder
		surfaceHolder.setFormat(PixelFormat.TRANSPARENT);
		surfaceHolder.addCallback(this);
		setFocusable(true);
		setZOrderOnTop(true);
		frameCount = 0;
	}
	
	public BindDeviceVoiceView(Context context, AttributeSet set) {
		super(context, set);
		this.context = context;
		surfaceHolder = this.getHolder();// 获取holder
		surfaceHolder.setFormat(PixelFormat.TRANSPARENT);
		surfaceHolder.addCallback(this);
		setFocusable(true);
		setZOrderOnTop(true);
		frameCount = 0;
	}
	
	
	@Override
	public void setVisibility(int visibility) {
		state = visibility;
		if (visibility == 0) {
			if(isSwiperOn == true) return;
			isSwiperOn = true;
		} else if(visibility == 2){
			
		}else{
			if(isSwiperOn == false) return;
			isSwiperOn = false;
		}
		rotate = 0;
		if (isSwiperOn) {
			titleImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.skz);
		} else
			titleImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.crvpos);
			vposImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.vpos);

	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_UP){
			if(backLeftMin < event.getX()&&event.getX()<backLeftMax &&
					0 < event.getY() && event.getY()<backHeightMax){
//				ScriptEngine.getInstance().execute("goLastPage", new Object[]{});
			}
		}
		return true;
	}
	private void  init(){

		cardImage = BitmapFactory.decodeResource(getResources(), R.drawable.sk);
		icCardWidth =  cardImage.getHeight();
		if (isSwiperOn) {
			titleImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.skz);
		} else
			titleImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.crvpos);
		vposImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.vpos);

		phoneImage = BitmapFactory.decodeResource(getResources(),
				R.drawable.iphone);
		/*vposImageFront = BitmapFactory.decodeResource(getResources(),
				R.drawable.name);*/
		backImage = BitmapFactory.decodeResource(getResources(),
				R.drawable.erro);
		backLeftMin = ConnectSwiperActivity.screenWidth - backImage.getWidth()-20*getResources().getDisplayMetrics().density;
		backHeightMin = 20*getResources().getDisplayMetrics().density;
		backHeightMax = backHeightMin+backImage.getHeight();
		backLeftMax = backLeftMin+backImage.getWidth();
		top = (int) (backImage.getHeight()+46*getResources().getDisplayMetrics().density);
		spacePostion = 20;
		topPosition = (ConnectSwiperActivity.screenHeight - titleImage.getHeight()
				- phoneImage.getHeight() - cardImage.getWidth() - spacePostion) / 2;
		if(top > topPosition)
			top = topPosition;
		else
			topPosition = top;
	}
	public void doDestroy() {
		try{
		thread.isDo = false;
		thread.interrupt();
			/*if(MainActivity.da!=null)
				MainActivity.da.dismiss();*/
						if(cardImage!=null && !cardImage.isRecycled()){
							cardImage.recycle();
							cardImage = null;
						}

						if(titleImage!=null && !titleImage.isRecycled()){
							titleImage.recycle();
							titleImage = null;
						}

						if(vposImage!=null && !vposImage.isRecycled()){
							vposImage.recycle();
							vposImage = null;
						}
			
						if(phoneImage!=null && !phoneImage.isRecycled()){
							phoneImage.recycle();
							phoneImage = null;
						}


						if(backImage!=null && !backImage.isRecycled()){
							backImage.recycle();
							backImage = null;
						}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 自定义线程类
	class MyThread extends Thread {
		public boolean isDo = true;
		@Override
		public void run() {
			init();
			while(isDo && ! this.isInterrupted() )
			{
					update();
			}
		}
	}
	
	//Caojun
	private void paint(Canvas canvas)
	{
		try {
			synchronized (surfaceHolder) {
				// ----------------首次进入停止几秒再进行动�?-----------------------
//				if (frameCount == 1) {
//					if(ClientEngine.getInstance()!=null)
//						Thread.sleep(400);
//					else
//						Thread.sleep(100);
//				}
				if(surfaceHolder==null)
					return;
				if(canvas==null ||	cardImage ==null || cardImage.isRecycled()||
						titleImage ==null || titleImage.isRecycled()||
						vposImage ==null || vposImage.isRecycled()||
						phoneImage ==null || phoneImage.isRecycled()||
						backImage ==null || backImage.isRecycled())
					return;
				canvas.drawColor(Color.TRANSPARENT,Mode.CLEAR);
				Paint mPaint = new Paint();
				mPaint.setAntiAlias(true);
				mPaint.setDither(true);
				// 绘制背景
//				if (frameCount < praitTime) {
//					canvas.drawBitmap(BackgroundImage, 0, 0, mPaint);
//				} else {
//					canvas.clipRect(new Rect(0, topPosition,
//							MainActivity.screenWidth, topPosition
//									+ titleImage.getHeight() + spacePostion
//									+ cardImage.getHeight()));
//					canvas.drawBitmap(BackgroundImage, 0, 0, mPaint);
//				}
				// mPaint.setColor(Color.WHITE);
				// 清屏
				// canvas.drawRect(0, 0, 720, 480, mPaint);
				
				// 创建矩阵以控制图片旋转和平移
				Matrix m = new Matrix();
				if ((isBack && !isVposIC)||(!isSwiperOn && isBack)) {
					float displacement = (rotate) / 5;
					if (displacement <= 1) {
						rotate = rotate - 1;
					} else {
						rotate = rotate - displacement;
					}
					if (rotate <= 0) {
						rotate = 0;
						isBack = false;
					}
					rotate = 0;
				}
				//比例
				float sacleSize = 0.67f;
				if(isVposIC){
					sacleSize = 0.75f;
				}
				int maxPosition = topPosition + titleImage.getHeight()
						+ spacePostion + cardImage.getWidth()
						- (int) (vposImage.getHeight() * sacleSize);
				if (isSwiperOn) {
					if(cardImage ==null || cardImage.isRecycled()||
							vposImage ==null || vposImage.isRecycled())
						return;
					if(isVposIC || !isBack){
						rotate += 2.5 * getResources().getDisplayMetrics().density;
					}
					if (!isBack) {
						m.postTranslate(rotate,
								topPosition + titleImage.getHeight()
								+ spacePostion + cardImage.getWidth()-cardImage.getHeight()- (int) (vposImage.getHeight() * 0.15));
					}else if(isVposIC){
						m.postRotate(-90);
						m.postTranslate((ConnectSwiperActivity.screenWidth - icCardWidth)/2,
								top+cardImage.getWidth() + rotate - vposImage.getHeight());
					}
					float position = topPosition + titleImage.getHeight()
					+ spacePostion + cardImage.getWidth()
					- (int) (vposImage.getHeight() * sacleSize);
					if(isBack || !isVposIC){
						canvas.drawBitmap(cardImage, m, mPaint);
					}
					//调换画布的先后位置，让卡在后面刷卡动作�?�真
					if(!isBack && isVposIC){
						canvas.drawBitmap(cardImage, m, mPaint);
					}
					canvas.drawBitmap(
							vposImage,
							(ConnectSwiperActivity.screenWidth - vposImage.getWidth()) / 2-60,
							position,
							mPaint);
					// 休眠以控制最大帧频为每秒�?30�?
					if (rotate > ConnectSwiperActivity.screenWidth * 0.8) {
						Thread.sleep(200);
						isBack = true;
						rotate = 0;
					}
					if(isBack && isVposIC){
						if(top+cardImage.getWidth() + rotate - vposImage.getHeight() > topPosition + titleImage.getHeight()
								+ cardImage.getWidth()){
							Thread.sleep(200);
							isBack = false;
							rotate = 0;
						}
					}
				} else {
					if (!isBack) {
						rotate += 0.8 * getResources().getDisplayMetrics().density;
					}
					float nextPosition = rotate + topPosition
							+ titleImage.getHeight() + spacePostion;

					m.postTranslate(
							(ConnectSwiperActivity.screenWidth - vposImage.getWidth()) / 2-60,
							nextPosition);

					canvas.drawBitmap(vposImage, m, mPaint);
					if (nextPosition > maxPosition) {
						if (state == 2) {
							rotate -= 0.8 * getResources()
									.getDisplayMetrics().density;
						} else {
							Thread.sleep(200);
							isBack = true;
						}
					}
				}
				canvas.drawBitmap(titleImage,
						(ConnectSwiperActivity.screenWidth - titleImage.getWidth()) / 2,
						top/2, mPaint);
//				if (frameCount < praitTime) {
					if(phoneImage ==null || phoneImage.isRecycled())
						return;
					canvas.drawBitmap(
							phoneImage,
							(ConnectSwiperActivity.screenWidth - phoneImage.getWidth()) / 2,
							topPosition + titleImage.getHeight()
							+ spacePostion+ cardImage.getWidth(),
							mPaint);
//				}
				if(isSwiperOn && isVposIC){
					/*canvas.drawBitmap(
							vposImageFront,
							(MainActivity.screenWidth - vposImage.getWidth()) / 2,
							topPosition + titleImage.getHeight()
							+ spacePostion + cardImage.getWidth()
							- (int) (vposImage.getHeight() * sacleSize),
							mPaint);*/
				}else if(isVposIC){
					/*canvas.drawBitmap(vposImageFront, m, mPaint);*/
				}
//				canvas.drawBitmap(
//						backImage,
//						/*20*getResources().getDisplayMetrics().density,*/
//						ConnectSwiperActivity.screenWidth- backImage.getWidth() - 20*getResources().getDisplayMetrics().density,
//						20*getResources().getDisplayMetrics().density,
//						mPaint);

				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (canvas != null)
						surfaceHolder.unlockCanvasAndPost(canvas);// 解锁画布，提交画好的图像
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}
	private void update()
	{
//		isPainted = false;
		frameCount++;
		Canvas canvas = null;
		try
		{
			if (frameCount < praitTime) {
				canvas = surfaceHolder.lockCanvas(null);// 获取画布
			} else {
				canvas = surfaceHolder.lockCanvas(new Rect(0, /*topPosition*/0,
						ConnectSwiperActivity.screenWidth, topPosition
								+ titleImage.getHeight() +3+ spacePostion
								+ cardImage.getWidth()+(int) (vposImage.getHeight() * 0.25)));
			}
			if (canvas != null)
			{   //同步holder
				synchronized (surfaceHolder)
				{   
					paint(canvas);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
//		finally
//		{
//			// do this in a finally so that if an exception is thrown
//			// during the above, we don't leave the Surface in an
//			// inconsistent state
//			if (canvas != null)
//			{
//				surfaceHolder.unlockCanvasAndPost(canvas);
//			}
//			canvas = null;
//		}
	}


	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
	}


	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread = new MyThread();
		thread.start();
	}


	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		doDestroy();
		
	}
}
